package com.pan.insist.util;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.pan.insist.constant.CommonConstant;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * FastDfs上传|下载|删除文件工具
 * </p>
 *
 * @author kaiji
 * @since 2019/12/9 09:37
 */
@Component
public class FastDFSUtil {

    @Resource
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 上传
     *
     * @param file
     *  上传文件
     * @return
     *      文件路径
     * @throws IOException 异常信息
     */
    public String upload(MultipartFile file) throws IOException {
        // 设置文件信息
        Set<MetaData> metaData = getMetaData(file);
        // 上传
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                metaData);
        return storePath.getFullPath();
    }

    /**
     * <p>
     *  上传图 并且生成缩略图
     * </p>
     *
     * @param  file
     *     上传文件
     * @return 图片地址
     */
    public String uploadCrtThumbImage(MultipartFile file) throws IOException {
        Set<MetaData> metaData = getMetaData(file);
        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), metaData);
        return storePath.getFullPath();
    }
    /**
     * 删除
     *
     * @param path
     *      文件路径
     */
    public void delete(String path) {
        fastFileStorageClient.deleteFile(path);
    }

    /**
     * 删除
     *
     * @param group
     *      文件的分组
     * @param path
     *      文件地址
     */
    public void delete(String group, String path) {
        fastFileStorageClient.deleteFile(group, path);
    }

    /**
     * 文件下载
     *
     * @param path     文件路径，例如：/group1/path=M00/00/00/itstyle.png
     */
    public byte[] download(String path) {
        // 获取文件
        StorePath storePath = StorePath.parseFromUrl(path);
        return fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
    }

    /**
     * 设置文件元数据
     *
     * @param file
     *      文件
     * @return  文件元数据
     */
    private Set<MetaData> getMetaData(MultipartFile file) {
        Set<MetaData> metaData = new HashSet<>(CommonConstant.DEFAULT_INITIAL_CAPACITY);
        metaData.add(new MetaData("author", "kaiJi"));
        metaData.add(new MetaData("description", file.getOriginalFilename()));
        return metaData;
    }
}
